import hashlib
import http.client
import json
import random
import urllib.parse

from flask_restful import Resource, reqparse, marshal_with, fields


class Translate(Resource):
    apiInfo = {
        'apiUrl': 'https://openapi.youdao.com/api',
        'appKey': "3b1a864564c147f4",
        'keyt': 'wlDpmVmMNYMRstUKUL0SiVUd9DWmLrP6',
    }

    response_fields = {
        'errorCode': fields.String,
        'message': fields.String,
        'translation': fields.List(fields.String),
        'basic': fields.Nested({
            'exam_type': fields.List(fields.String),
            'us_phonetic': fields.String,
            'uk_phonetic': fields.String,
            'us_speech': fields.String,
            'explains': fields.List(fields.String)
        }),
        'tSpeakUrl': fields.String
    }

    httpClient = None

    def get(self):
        return self.apiInfo

    @marshal_with(response_fields)
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('q', type=str)
        parser.add_argument('fromLang', type=str)
        parser.add_argument('toLang', type=str)
        args = parser.parse_args()
        q = args['q']
        fromLang = args['fromLang']
        toLang = args['toLang']
        salt = random.randint(1, 65536)
        sign = self.apiInfo['appKey'] + q + str(salt) + self.apiInfo['keyt']
        sign = hashlib.md5(sign.encode("utf-8")).hexdigest()
        # m1 = md5.new()
        # m1.update(sign)
        # sign = m1.hexdigest()
        myurl = self.apiInfo['apiUrl'] + '?appKey=' + self.apiInfo['appKey'] + '&q=' + urllib.parse.quote(
            q) + '&from=' + fromLang + '&to=' + toLang + \
                '&salt=' + str(salt) + '&sign=' + sign
        httpClient = None
        try:
            httpClient = http.client.HTTPConnection('openapi.youdao.com')
            httpClient.request('GET', myurl)
            # response是HTTPResponse对象
            response = httpClient.getresponse()
            jsonResponse = response.read().decode("utf-8")
            dictResponse = json.loads(jsonResponse)  # 获得返回的结果，结果为dict格式
            basic, exam_type, us_phonetic, uk_phonetic, us_speech, explains = {}, [], '', '', '', []
            if dictResponse.__contains__('basic'):
                if dictResponse['basic'].__contains__('exam_type'):
                    exam_type = dictResponse['basic']['exam_type']
                if dictResponse['basic'].__contains__('us-phonetic'):
                    us_phonetic = dictResponse['basic']['us-phonetic']
                if dictResponse['basic'].__contains__('uk-phonetic'):
                    uk_phonetic = dictResponse['basic']['uk-phonetic']
                if dictResponse['basic'].__contains__('us_speech'):
                    us_speech = dictResponse['basic']['us_speech']
                if dictResponse['basic'].__contains__('explains'):
                    explains = dictResponse['basic']['explains']
                basic = dict(exam_type=exam_type, us_phonetic=us_phonetic, uk_phonetic=uk_phonetic, us_speech=us_speech,
                             explains=explains)
            data = dict(errorCode=dictResponse['errorCode'], message=dictResponse['errorCode'],
                        translation=dictResponse['translation'], basic=basic,
                        tSpeakUrl=dictResponse['tSpeakUrl'])
            return data, 200
        except Exception as e:
            print(e)
        finally:
            if httpClient:
                httpClient.close()
